import webapp2
from google.appengine.ext.webapp.util import run_wsgi_app
from webapp2 import uri_for
from google.appengine.ext import db


class Order(db.Model):
	i = db.StringProperty()
	j = db.StringProperty()


def write_table():
	s = """"""
	orders = db.GqlQuery("SELECT *")
	for order in orders:#filling array a with orders from base
		a[int(order.i)][int(order.j)] += 1
		summ[int(order.i)] += 1

	drinks = ['Kefir', 'Ryazhenka', 'Snowball', 'Milk']

	fin = open('page_begin.htm', 'r')#Writing begin of page html-code from file
	for x in fin.readlines():
		s += x
	fin.close()

	for i in range(4):#writing table from array a
		s += '<tr>\n'
		s += '<td>' + drinks[i] + '</td>\n'
		for j in range(34):
			s += '<td>' + str(a[i][j]) + '</td>\n'
		s += '<td>' + str(summ[i]) + '</td>\n'
		s += '</tr>\n'

	fin = open('page_end.htm')#writing end of page html-code from file
	for x in fin.readlines():
		s += x
	fin.close()

	return s



class ShowPage(webapp2.RequestHandler):
	def get(self, *args, **kwargs):
		self.response.write(write_table() % (uri_for('send')))


class Send(webapp2.RequestHandler):
	def get(self, *args, **kwargs):
		self.redirect(uri_for('show'))
	def post(self, *args, **kwargs):
		order = Order()
		drinks = ['Kefir', 'Ryazhenka', 'Snowball', 'Milk']
		s = str(self.request.get('Drink'))
		order.i = str(drinks.index(s))
		rm = str(self.request.get('House'))
		order.j = str(int(rm[5:]) - 1)
		order.put()
		self.redirect(uri_for('show'))


a = [[0 for i in range(34)] for j in range(4)]
summ = [0] * 4
routes = [
	webapp2.Route(
		'/',
		handler = ShowPage,
		name = 'show'),
	webapp2.Route(
		'/send',
		handler = Send,
		name = 'send'),]
application = webapp2.WSGIApplication(routes, debug = True)
run_wsgi_app(application)